import { NextFunction, Request, Response } from 'express';
import UserService from '../services/UserService';

class UserController {
  // 注册
  public async createUser(req: Request, res: Response, next: NextFunction) {
    try {
      const userParams = req.body;
      const user = await UserService.createUser(userParams);
      res.locals.data = user;
      next();
    } catch (error) {
      res.locals.error = error;
      next();
    }
  }
  // 获取用户信息
  public async getUserById(req: Request, res: Response, next: NextFunction) {
    try {
      const userId = req.query?.userId as string||'';
      const user = await UserService.getUserById(userId);
      res.locals.data = user;
      next();
    } catch (error) {
      res.locals.error = error;
      next();
    }
  }
  // 登录
  public async userLogin(req: Request, res: Response, next: NextFunction) {
    try {
      const userParams: { username: string; password: string } = req.body;
      const loginResult = await UserService.userLogin(userParams);
      switch (loginResult.code) {
        case 200: {
          res.locals.data = loginResult.token;
          break;
        }
        case 401: {
          res.locals.error = loginResult;
          break;
        }
        default: {
          res.locals.error = '内部错误，登录失败';
          /** empty */
        }
      }
      next();
    } catch (error) {
      res.locals.error = error;
      next();
    }
  }
}

export default new UserController();
